<template>
  <el-dialog 
    :title="title" 
    :visible.sync="visible" 
    width="800px" 
    append-to-body 
    class="excel-upload-dialog"
    @close="handleClose"
  >
    <div class="excel-upload-container">
      <div class="steps-container">
        <div class="step-item">
          <div class="step-number">
            <i class="el-icon-s-operation"></i>
            <span>1</span>
          </div>
          <div class="step-content">
            <div class="step-title"><i class="el-icon-setting step-icon"></i>选择新建方式</div>
            <div class="step-form">
              <el-radio-group v-model="uploadForm.buildType">
                <el-radio :label="1"><span class="radio-text">仅在主档新建</span></el-radio>
                <el-radio :label="2"><span class="radio-text">在主档新建并同步到门店</span></el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>

        <div class="step-item">
          <div class="step-number">
            <i class="el-icon-download"></i>
            <span>2</span>
          </div>
          <div class="step-content">
            <div class="step-title"><i class="el-icon-document step-icon"></i>下载模版并填写</div>
            <div class="step-desc">请按照模版格式填写Excel表格内容，表格数据最多支持1000条</div>
            <div class="template-download">
              <div class="template-file">
                <i class="el-icon-document-copy"></i>
                <span>{{ templateName }}</span>
              </div>
              <el-button 
                type="primary" 
                size="small" 
                class="download-btn" 
                icon="el-icon-download"
                @click="downloadTemplate"
              >
                下载模板
              </el-button>
            </div>
          </div>
        </div>

        <div class="step-item">
          <div class="step-number">
            <i class="el-icon-upload2"></i>
            <span>3</span>
          </div>
          <div class="step-content">
            <div class="step-title"><i class="el-icon-upload step-icon"></i>上传文件并提交系统</div>
            <div class="step-desc">提交后系统需要一段时间进行处理</div>
            <div class="upload-area">
              <el-upload
                class="upload-dragger"
                drag
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :file-list="fileList"
                :limit="1"
                accept=".xls,.xlsx"
              >
                <div class="upload-content">
                  <i class="el-icon-upload upload-icon"></i>
                  <div class="upload-text">
                    请点击或拖拽文件至此上传
                    <div class="upload-hint">支持 .xls、.xlsx 格式的文件</div>
                  </div>
                </div>
              </el-upload>
              
              <!-- 文件上传后的状态显示 -->
              <div v-if="fileStatus.name" class="upload-status">
                <div class="file-info">
                  <i class="el-icon-document file-icon"></i>
                  <span class="file-name">{{ fileStatus.name }}</span>
                  <span class="file-size">{{ formatFileSize(fileStatus.size) }}</span>
                </div>
                <el-progress 
                  :percentage="uploadProgress" 
                  :status="uploadStatus"
                  :stroke-width="8"
                ></el-progress>
                <div class="upload-message">{{ uploadMessage }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose" icon="el-icon-close">取 消</el-button>
      <el-button 
        type="primary" 
        @click="submitUpload" 
        :disabled="!hasFile || uploading" 
        :loading="uploading"
        icon="el-icon-check"
      >
        {{ uploading ? '上传中' : '确 定' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { uploadFile } from '@/api/business/goodForm'

export default {
  name: 'ExcelUpload',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: 'Excel上传'
    },
    type: {
      type: String,
      required: true,
      validator(value) {
        return ['main', 'spec'].indexOf(value) !== -1
      }
    }
  },
  data() {
    return {
      uploadForm: {
        buildType: 1
      },
      fileList: [],
      uploadProgress: 0,
      uploadStatus: '',
      uploadMessage: '',
      uploading: false,
      fileStatus: {
        name: '',
        size: 0
      }
    }
  },
  computed: {
    templateName() {
      return this.type === 'main'
        ? '批量新增总部商品模板.xlsx'
        : 'Excel批量新建规格模板.xlsx'
    },
    hasFile() {
      return this.fileList.length > 0
    }
  },
  methods: {
    // 处理文件变更
    handleFileChange(file) {
      // 更新文件列表
      this.fileList = [file]
      
      // 更新文件状态信息
      if (file) {
        this.fileStatus = {
          name: file.name,
          size: file.size
        }
        this.uploadProgress = 0
        this.uploadStatus = ''
        this.uploadMessage = '文件已选择，点击确定开始上传'
      }
    },

    // 上传文件到服务器
    uploadFiles(file) {
      this.uploading = true
      this.uploadProgress = 0
      this.uploadMessage = '正在上传中，请稍候...'
      
      // 创建FormData
      const formData = new FormData()
      formData.append('file', file.raw)  // 获取文件的原始对象
      
      // 模拟上传进度
      const simulateProgress = () => {
        const interval = setInterval(() => {
          if (this.uploadProgress < 90) {
            this.uploadProgress += Math.floor(Math.random() * 10) + 1
          } else {
            clearInterval(interval)
          }
        }, 300)
        return interval
      }
      
      const progressInterval = simulateProgress()
      
      // 调用上传API
      uploadFile(formData).then(response => {
        clearInterval(progressInterval)
        this.uploadProgress = 100
        this.uploadStatus = 'success'
        this.uploadMessage = '文件上传成功！'
        this.$message.success('文件上传成功！')
        
        setTimeout(() => {
          this.notifyUploadSuccess()
        }, 1000)
      }).catch(error => {
        clearInterval(progressInterval)
        this.uploadProgress = 100
        this.uploadStatus = 'exception'
        this.uploadMessage = '上传失败，请重试！'
        this.$message.error('上传失败：' + (error.message || '未知错误'))
        this.uploading = false
      })
    },

    // 处理关闭弹窗
    handleClose() {
      this.uploadForm.buildType = 1
      this.fileList = []
      this.uploadProgress = 0
      this.uploadStatus = ''
      this.uploadMessage = ''
      this.fileStatus = { name: '', size: 0 }
      this.uploading = false
      this.$emit('update:visible', false)
    },
    
    // 下载模板
    downloadTemplate() {
      this.$message.success(`下载${this.templateName}模板`)

      // 模拟下载行为
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '#'
      link.setAttribute('download', this.templateName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    
    // 提交上传
    submitUpload() {
      if (!this.hasFile) {
        this.$message.warning('请先选择要上传的文件')
        return
      }
      
      // 开始上传文件
      this.uploadFiles(this.fileList[0])
    },
    
    // 通知上传成功
    notifyUploadSuccess() {
      this.$emit('upload-success', {
        type: this.type,
        buildType: this.uploadForm.buildType,
        file: this.fileList[0]
      })
      
      this.uploading = false
      
      // 延迟关闭，让用户看到上传完成的状态
      setTimeout(() => {
        this.handleClose()
      }, 500)
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  }
}
</script>

<style lang="scss" scoped>
.excel-upload-dialog {
  ::v-deep .el-dialog__header {
    background: linear-gradient(135deg, #409EFF, #3a8ee6);
    padding: 15px 20px;
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: #fff;
      font-weight: 600;
      font-size: 18px;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.9);
      
      &:hover {
        color: #fff;
      }
    }
  }
  
  ::v-deep .el-dialog__body {
    padding: 25px 20px;
  }
}

.excel-upload-container {
  padding: 0 20px;
}

.steps-container {
  display: flex;
  flex-direction: column;
}

.step-item {
  display: flex;
  margin-bottom: 30px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.step-number {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  flex-shrink: 0;
  position: relative;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
  
  i {
    font-size: 18px;
    position: absolute;
    top: 8px;
    left: 50%;
    transform: translateX(-50%);
  }
  
  span {
    position: relative;
    top: 5px;
  }
}

.step-content {
  flex: 1;
}

.step-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
  display: flex;
  align-items: center;
  
  .step-icon {
    margin-right: 8px;
    color: #409EFF;
  }
}

.step-desc {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.5;
}

.step-form {
  margin-top: 10px;
  
  .radio-text {
    margin-left: 4px;
    font-weight: 500;
  }
}

.template-download {
  display: flex;
  align-items: center;
  background-color: #eef5ff;
  padding: 15px;
  border-radius: 6px;
  margin-top: 10px;
  border-left: 4px solid #409EFF;
}

.template-file {
  flex: 1;
  display: flex;
  align-items: center;
  
  i {
    font-size: 22px;
    margin-right: 10px;
    color: #409EFF;
  }
  
  span {
    font-weight: 500;
    color: #303133;
  }
}

.download-btn {
  margin-left: 15px;
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
  border: none;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
}

.upload-area {
  margin-top: 15px;
  border-radius: 6px;
  overflow: hidden;
}

.upload-dragger {
  width: 100%;
  
  ::v-deep .el-upload {
    width: 100%;
    
    .el-upload-dragger {
      width: 100%;
      height: 180px;
      border: 2px dashed #d9d9d9;
      background-color: #fafafa;
      
      &:hover {
        border-color: #409EFF;
      }
      
      &.is-dragover {
        background-color: rgba(64, 158, 255, 0.1);
        border-color: #409EFF;
      }
    }
  }
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.upload-icon {
  font-size: 48px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  color: #606266;
  font-size: 16px;
  text-align: center;
  margin: 10px 0;
}

.upload-hint {
  font-size: 13px;
  color: #909399;
  margin-top: 8px;
}

.upload-status {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  margin-top: 15px;
  border: 1px solid #ebeef5;
}

.file-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  .file-icon {
    font-size: 20px;
    color: #409EFF;
    margin-right: 10px;
  }
  
  .file-name {
    font-weight: 500;
    color: #303133;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .file-size {
    font-size: 12px;
    color: #909399;
    margin-left: 10px;
  }
}

.upload-message {
  font-size: 13px;
  color: #606266;
  margin-top: 8px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  
  .el-button + .el-button {
    margin-left: 15px;
  }
}
</style>